package com.pjnkj.thunder.dagger.convert;

import com.alibaba.fastjson.JSONObject;
import com.pjnkj.thunder.dagger.common.Sheath;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class HttpJson extends Sheath {


    public HttpJson(Object o) {
        String simpleName = o.getClass().getSimpleName();
        if (simpleName.equals("RequestFacade") || simpleName.equals("StandardMultipartHttpServletRequest") ) {
            this.request((HttpServletRequest) o);
        } else {

            this.response(o);
        }
    }


    private void request(HttpServletRequest request) {

        try {
            Map<String, String[]> parameterMap = request.getParameterMap();

            Map<String, java.lang.Object> paramsMap = new HashMap<>(parameterMap.size());
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                java.lang.Object valueStr = (entry.getValue() == null) ? null : entry.getValue()[0];
                paramsMap.put(entry.getKey(), valueStr);
            }

            this.setObject(paramsMap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void response(Object o) {
        this.setObject(JSONObject.toJSON(o).toString());
    }
}
